import Taro, {Component, Config} from "@tarojs/taro";
import { AtToast } from "taro-ui"
import {toJS} from 'mobx'
import {inject, observer} from '@tarojs/mobx'
import {View, Image, Text, RichText, Swiper, SwiperItem, ScrollView, Map} from "@tarojs/components";
import {getRuntime, htmlToText, ServerHost} from '../../utils/common'
import {IStoreProps} from '../../store/Stores'

import './mall.less'
import './detail.less'
import share from "../../assets/img/icon_46.png";
import right from "../../assets/img/right.png";
import close from "../../assets/img/close.png";
import reduce from "../../assets/img/icon_65.png";
import add from "../../assets/img/icon_66.png";
import share_icon from "../../assets/img/share_arrow.png";
import close_icon from "../../assets/img/icon_close_bold.png";


// 商品详情
interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class MallDetail extends Component<IHomeProps> {
  constructor(porps) {
    super(porps)
  }

  state = {
    selectSpec: false, // 控制规格弹窗
    info: {}, // 商品详情信息
    infoBanner:[],
    itemNum: 1, // 购买商品数量
    sku: [], // 规格数组
    selectedSku:[], // 选择的规格
    specNoId:null, // 已选规格规格ID
    specObj:null, // 已选规格描述
    specStrArr:['选择'], // 选择规格字符串
    specNo:Array(), // 当前选择规格数组
    itemSpecs: [], // 规格匹配的价格数组
    isTips: false,
    tipsText: '',
    isShare: false
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({title: '礼品定制详情'})
    let id = parseInt(this.$router.params.id)
    this.getJsApiParam()
    if (id) { this.getItemInfo(id) }
  }

  getItemInfo(id:number) {
    let { PointMallStore } = this.props.stores
    PointMallStore.getItemInfo({
      formId:id,
      callback:res => {
        let resObj = toJS(res)
        let infoBanner = resObj.pictures.split(',')
        let sku =  resObj.itemSkuCategories || []
        //let sku =  this.state.sku
        // 初始化需要选择的规格
        let specStrArr = ['选择']
        let specNo = Array(sku.length).fill(null)
        sku&&sku.map((item,index) => {
          specStrArr.splice(index+1,1, item.name)
        })
        this.setState({
          info: resObj,
          infoBanner,
          sku,
          itemSpecs: res.itemSpecs,
          specStrArr,
          specNo
        }, () => {
          this.share()
        })
      }
    })
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  // 打开规格弹窗
  selectSpec () {
    this.setState({
      selectSpec: !this.state.selectSpec
    })
  }

  // 关闭规格选择框
  closeSpec (e) {
    e.stopImmediatePropagation()
    this.setState({
      selectSpec: false
    },() => {
      this.setStorage()
    })
  }

  // 点击规格选择时不会关闭弹出框
  openSpec (e) {
    e.stopPropagation()
    this.setState({
      selectSpec: true
    })
  }

  /**
   * 选择规格
   * @param column 选择的规格类别索引
   * @param id 选择的规格ID
   */
  selectOption(column:number, id: number) {
    let { specStrArr,specNo,itemSpecs } = this.state
    let specStr = ''
    let specStrTemp = []
    let specNoId = null
    let specObj = null
    // let specNoTemp = []
    specNo.splice(column,1,id)
    // 更新规格显示字段spcStr
    let temp = specNo.filter(item => item)
    if(specNo.length === temp.length){
      // 已选全部规格,匹配规格字符串得出价格
      itemSpecs.map(item => {
        if(item.specNo === specNo.join('-')){
          specNoId = item.id
          specObj = item
        }
      })
    }else {
      // 还有未选规格
      specNo.map((item,index) => {
        if(item){
          // 删除已选项
          specStrArr.splice(index+1,1)
        }
      })
    }
    this.setState({
      specStrArr,
      specNo,
      specNoId,
      specObj
    })
  }

  // 选择购买数量
  selectItemNum(type:string) {
    let { itemNum } = this.state
    if(type==='reduce'){
      // 减商品
      if(itemNum<=1){
        return
      }
      itemNum--
    }else {
      // 加商品
      itemNum++
    }
    this.setState({
      itemNum
    },() => {
      this.setStorage()
    })
  }

  // 缓存商品信息和所选规格信息
  setStorage() {
    let { info,itemNum,specNo,specNoId,specObj } = this.state
    if(specNoId){
      let cart = {
        itemId: info.id,
        name: info.name,
        picture: info.picture,
        freight: info.freight,
        publicDonations: info.publicDonations, // 公益捐款比列
        pointValue: info.pointValue, // 积分兑换现金比列
        specNo,
        itemNum,
        specNoId,
        itemSpec: specObj.spec,
        itemSignPrice: specObj.price,
        itemPrice: (Math.round(specObj.price*itemNum*100))/100
      }
      getRuntime().setStorage('userCart',cart)
     // this.setCart(cart)
    }else {
      return
    }
  }

  /**
   * @param data 缓存数据
   * @param type 缓存类型 add/reduce
   */
  setCart(data: object) {
    // debugger
    if(!data) return
    let flag = false
    // 存在商品ID修改，不存在增加
    let userCart =  getRuntime().getStorage('userCart') || []
    /*console.log('缓存值')
    console.log(userCart)*/
    userCart.map((item,index) => {
      if(item.itemId === data.itemId){
        userCart.splice(index,1,data)
        flag = true
      }
    })
    if(!flag){
      userCart.push(data)
    }
    getRuntime().setStorage('userCart',userCart)
  }

  // 购买按钮(下单)
  placeOrder(type: number = 1) {
    if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    // 规格验证
    let { itemNum, specNoId, specObj } = this.state
    let { PointMallStore } = this.props.stores
    if(!specNoId&&type===2){this.setState({ selectSpec: true }); return}
    if(!specNoId){getRuntime().showToast('请选择规格~'); return}
    this.setStorage()
    /* PointMallStore.placeOrder({
       form: {
         itemSpecId: specNoId,
         qty: itemNum
       },
       callback: res => {
         console.log(res)
       }
     })*/
    getRuntime().navigateTo(`/pages/mall/order_confirm_custom?id=${this.state.info.id}&type=custom`)
  }

  getJsApiParam = () => {
    let currentUrl = window.location.href
    let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`
    Taro.showLoading({title: '加载中...'})
    fetch(apiUrl, {
      method: 'GET',
      mode: "cors",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin'
    })
      .then(response => {
        Taro.hideLoading()
        return response.json()
      })
      .then(response => {
        let appId = response.appId
        let timestamp = response.timestamp
        let nonceStr = response.nonceStr
        let signature = response.signature
        this.setState({ wxConfig: response })
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appId, // 必填，公众号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature,// 必填，签名
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      })
      .catch(error => {
        console.log(error)
      })
  }

  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let item = this.state.info
    let url1 = ServerHost+'/m/#/pages/mall/custom_detail?id='+item.id
    let title = item.name
    let desc = htmlToText(item.content)
    let imgUrl = item.picture
    var shareData = {
      title,
      desc,
      imgUrl,
      otherImgUrl: '',
      url: window.location.href,
      link: window.location.href
    };
    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
  }

  btnShare() {
    this.setState({ isShare: true })
  }

  onClose() {
    this.setState({ isShare: false })
  }

  componentDidHide(): void {
    this.setState({ isShare: false })
  }

  render() {
    let { info,infoBanner,selectSpec,itemNum, sku,specObj,specStrArr,specNo,isShare } = this.state
    let showSpecStr = specStrArr.join(' ')
    let totalPrice: any = '0.00'
    let specItemNum: any = 0
    // console.log(specObj)
    // console.log(itemNum)
    if(specObj){
      totalPrice = (Math.round(specObj.price*itemNum*100))/100
      specItemNum = itemNum
    }
    return (
      <View className='mall-detail'>
        <View className='swiper-wrap'>
          <Swiper className='swiper' indicatorColor='#fff' indicatorActiveColor='#00a0e9'
                  circular
                  indicatorDots
                  autoplay={true}
          >
            {infoBanner&&
            infoBanner.map(item => {
              return(
                <SwiperItem className='swiper-item'>
                  <Image className='swiper-img' src={item} />
                </SwiperItem>
              )
            })
            }
          </Swiper>
        </View>

        <View className='share-info'>
          <View className='line'>
            <View className='title'>{info.name}</View>
            <View className='btn-share' onClick={this.btnShare.bind(this)}>
              <Image className={'share-icon'} src={share} />
              <Text className='share-name'>分享</Text>
            </View>
          </View>
          <View className='line line2'>
            <View className='price'>
              <Text className='list-small'>￥</Text>
              <Text className='list-price'>{info.price}</Text>
              <Text className='list-old-price'>￥{info.originalPrice}</Text>
            </View>
            <View className='all'>运费 <Text className={'count'}>￥{info.freight}</Text></View>
          </View>
        </View>
        <View className='interval' />

        <View className='select-spec' onClick={this.selectSpec.bind(this)}>
          <View className='title'>请选择规格数量</View>
          <View className='drop-down-con'>
            <Text className='con'>{itemNum}</Text>
            <Image className='drop-down-icon' src={right} />
          </View>
        </View>
        <View className='interval' />

        <View className='column-title content-30'>
          <Text className='column-name'>商品详情</Text>
        </View>

        <View className='detail-info rich-text'>
          <RichText className='rt' nodes={info.content} />
        </View>

        <View className='footer-block' />
        <View className='footer-block' />

        <View className={selectSpec ? 'spec-fixed  spec-fixed-active' : 'spec-fixed '}
              onClick={this.closeSpec.bind(this)}
        >
          <View className='spec-content' onClick={this.openSpec.bind(this)}>
            <View className='item item1'>
              <Image src={specObj?specObj.picture:info.picture} className='item1-img' />
              <View className='info'>
                <View className='line color'>
                  <Text className='list-small'>￥</Text>
                  <Text className='list-price'>{specObj?specObj.price:info.price}</Text>
                </View>
                <View className='list-title'>
                  {/*已选规格*/}
                  {specObj?specObj.spec:showSpecStr }
                </View>
              </View>
              <Image src={close} className='btn-close' onClick={this.closeSpec.bind(this)} />
            </View>
            <ScrollView scrollY={true} className='overflow'>
              {sku.length>0&&
              sku.map((item,index) => {
                return(
                  <View className='item item2' key={item.id}>
                    <View className='spec-name list-title'>{item.name}</View>
                    <View className='option'>
                      {
                        item.itemSkus.map(option => {
                          return(
                            <Text className={specNo[index] === option.id?'op op-active':'op'}
                                  key={option.id}
                                  onClick={this.selectOption.bind(this,index,option.id)}
                            >{option.sku}</Text>
                          )
                        })
                      }
                    </View>
                  </View>
                )
              })
              }
              <View className='item buy-count'>
                <View className='spec-count list-title'>购买数量</View>
                <View className='spec-count-control'>
                  <View className={itemNum<2?'btn reduce disabled':'btn reduce'} onClick={this.selectItemNum.bind(this,'reduce')}> - </View>
                  <Text className='btn count'> {itemNum} </Text>
                  {/* <Image className='btn add' src={add} onClick={this.selectItemNum.bind(this,'add')} />*/}
                  <View className='btn add' onClick={this.selectItemNum.bind(this,'add')}> + </View>
                </View>
              </View>
            </ScrollView>
            <View className='item item4' onClick={this.placeOrder.bind(this, 1)}>
              <View className='page-submit'>立即购买</View>
            </View>
          </View>
        </View>

        <View className='page-footer2'>
          <View className='all-price'>
            已选 <Text className='color all-count'>{specItemNum}</Text> 件商品，合计：
            <Text className='color'> <Text className='list-small'>￥</Text>{totalPrice}</Text>
          </View>
          <View className='btn-submit' onClick={this.placeOrder.bind(this, 2)}>立即购买</View>
        </View>

        <View className={isShare?'share-arrow share-arrow-active':'share-arrow'}>
          <Image className='share-arrow-icon' src={share_icon} />
          <View className='con'>
            <View>请点击右上角</View>
            <View>通过【发送给朋友】</View>
            <View>分享给好友</View>
          </View>
          <Image className='close-icon' onClick={this.onClose.bind(this)} src={close_icon} />
        </View>
      </View>
    )
  }
}

export default MallDetail
